package cn.qy.java.base.ch21;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 生产消费者问题
 */
public class Ch21_03_ProductCustomer {
	
	public static void main(String[] args) {
		int size = 3;
		MyBlockQueue queue = new MyBlockQueue(size);
		new Product(queue).start();
		new Customer(queue).start();
	}
	
	static class MyBlockQueue {
		final int size;
		final Deque<Integer> queue;
		
		MyBlockQueue(int size) {
			this.size = size;
			this.queue = new ArrayDeque<>(size);
		}

		public synchronized void push(Integer i) throws InterruptedException {
			// when is full
			while(this.queue.size() == size) {
				wait();
			}
			this.queue.addFirst(i);
			notifyAll();
		}
		
		public synchronized Integer pull() throws InterruptedException {
			// when is empty
			while(this.queue.isEmpty()) {
				wait();
			}
			Integer i = this.queue.pollFirst();
			notifyAll();
			return i;
		}
	}
	
	static class Product extends Thread {
		final MyBlockQueue queue;
		
		public Product(MyBlockQueue queue) {
			this.queue = queue;
		}

		@Override
		public void run() {
			int i = 0;
			while(true) {
				try {
					Thread.sleep(1000);
					this.queue.push(i);
					System.out.println("product " + i);
					i++;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	static class Customer extends Thread {
		final MyBlockQueue queue;
		
		public Customer(MyBlockQueue queue) {
			this.queue = queue;
		}

		@Override
		public void run() {
			while(true) {
				try {
					Thread.sleep(1000);
					System.out.println("consumer " + this.queue.pull());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
